from django.conf import settings
import variables


class CaptchaMiddleware(object):
    """
    Needed for Captcha field's work
    """
    
    variableName = 'captcha_code'  #default variable name
        
    def process_request(self, request):
        """
        Get's generated captcha code from sessions and save it into 'variables.code' variable
        """
        
        assert hasattr(request, 'session'), "The captcha middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
        variables.middleware_enabled = True
        
        if hasattr(settings, 'CAPTCHA_VARIABLE_NAME'):
            self.variableName = settings.CAPTCHA_VARIABLE_NAME

        #saving the code from session, setting None if not set
        variables.code =  request.session.get(self.variableName, None) 
        
        return None
